package com.heima.wemedia.service.impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    // 注入oss工具

    @Autowired
    FileStorageService fileStorageService;
    // 图片前缀

    @Value("${file.oss.prefix}")
    String prefix;
    //图片后缀

    @Value("${file.oss.web-site}")
    String webSite;


    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 检验数据
        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "传参有误");
        }
        // 获取线程中的id
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 获取上传的文件
        String file = multipartFile.getOriginalFilename();

        // 获取上传的文件后缀
        String suffix = file.substring(file.lastIndexOf("."));

        // 校验是否合格
        if (!checkFileSuffix(suffix)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文件格式仅支持(jpg png gif jpeg)");
        }
        // 修改名字
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");

        // 上传到oss
        try {
            fileName = fileStorageService.store(prefix, fileName + suffix, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败" + e.getMessage());
        }
        // 存放到对象
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(wmUser.getId());
        wmMaterial.setUrl(fileName);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        // 存入数据库 相对路线
        this.save(wmMaterial);

        // 返回给前端 绝对经
        wmMaterial.setUrl(webSite + wmMaterial.getUrl());
        return ResponseResult.okResult(wmMaterial);
    }

    // 分页查询

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        // 校验分页
        dto.checkParam();
        // 条件查询
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();

        // 当前登录用户的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        // 收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());

        // 时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        IPage<WmMaterial> iPage = this.page(page, wrapper);
        // 封装返回结果 添加路径
        List<WmMaterial> records = iPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }

        return new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
    }


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmMaterial wmMaterial = this.getById(id);
        // 业务处理
        //判断当前id是否被引用,如果被使用则禁止删除
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        // 删除库
        this.removeById(id);
        // 删除oss图片
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult();
    }

    /**
     * 修改收藏
     *
     * @param id   素材id
     * @param type 素材类型
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        // 检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材信息不存在");
        }

        Integer uid = WmThreadLocalUtils.getUser().getId();
        if (!wmMaterial.getUserId().equals(uid)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "只允许收藏自己上传的素材");
        }
        // 修改素材类型
        wmMaterial.setIsCollection(type);
        this.updateById(wmMaterial);
        return ResponseResult.okResult();
    }


    //校验后缀
    private boolean checkFileSuffix(String fileName) {
        if (StringUtils.isBlank(fileName)) return false;
        List<String> allowSuffix = Arrays.asList(".jpg", ".png", ".gif", ".gif");
        for (String suffix : allowSuffix) {
            if (suffix.equals(fileName)) {
                boolean isAllow = true;
                return isAllow;
            }
        }
        return false;
    }
}
